<!DOCTYPE html>
<html>
<title>Registration Page :: DIF233 - Unit 1 - Excercise 1</title>
<body>
	<?php
		function update_password($id, $new_password){
			$file_data = file("./shadow.txt");
			$file = fopen("./shadow.txt", "w");
			foreach($file_data as $value){
				$tokens = explode(":", $value);
				if(strcmp($tokens[1], $id) == 0){
					$tokens[2] = $new_password;
					$value = $tokens[0].":".$tokens[1].":".$tokens[2].":".$tokens[3].":".$tokens[4];
				}
				fwrite($file,$value);
			}
		}
		function is_valid_password($id, $password){
			$file_data = file("./shadow.txt");
			foreach($file_data as $value){
				$tokens = explode(":", $value);
				if(strcmp($tokens[1], $id) == 0 && strcmp($tokens[2], $password) == 0){
					return 1;
				}
			}
			return 0;
		}
		if(!empty($_GET["error"])){
				echo "<h3>Current password is wrong</h3>";			
		}
		if(!empty($_POST["Update"])){
			if(is_valid_password($_POST["id"], $_POST["current_passwd"])){
				update_password($_POST["id"], $_POST["new_passwd"]);
				header("Location: user.php?passwd=updated&id=".$_POST["id"]);
				exit();
			}else{
				echo "<h3>Current password is wrong</h3>";
				header("Location: password_change.php?error=pwdwrong&id=".$_POST["id"]);
				exit();
			}
		}
	?>
<form method="post" name="change_pword" action="password_change.php?id=<?php echo $_GET['id']; ?>">

	<table style="border=0">
		<tr>
			<td>
				Current Password:
			</td>
			<td>
				<input type="password" name="current_passwd" value="" placeholder="Your Current Password" required />
			</td>
		</tr>
		<tr>
			<td>
				New Password:
			</td>
			<td>
				<input type="password" name="new_passwd" value="" placeholder="Your New Password" required />
			</td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" name="Update" value="Update" /></td>
		</tr>		
	</table>
	<input type="hidden" name="id" value=<?php echo empty($_GET["id"])?$_POST["id"]:$_GET["id"]?> />
</form>
</body>
</html>
